package commands.community
{
	import cultu.community.message.Community;
	import cultu.community.message.CommunityCriteria;
	import cultu.community.message.CommunityList;
	import cultu.community.message.CommunityScenario;
	import cultu.community.service.CommunityManager;
	
	import flash.utils.Dictionary;
	
	import model.Model;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import vo.community.CommunityVO;
	
	import wizeoo.commands.WIZRemoteCall;

	public class FindCommunitiesCmd extends WIZRemoteCall
	{
		/**Référence au model*/
		private var mod:Model = Model.getInstance();
		
		public function FindCommunitiesCmd(pCallback:Function=null)
		{
			super(pCallback);
		}
		
		override public function wizExecute():void
		{
			var cm:CommunityManager = new CommunityManager();
			var cs:CommunityScenario = new CommunityScenario();
			var cc:CommunityCriteria = new CommunityCriteria();
			
			cs.manageProducts = false;
			
			cc.jpqlQuery = 'SELECT com FROM Community com';
			
			cm.addEventListener(ResultEvent.RESULT,result,false,0,true);
			cm.addEventListener(FaultEvent.FAULT,fault,false,0,true);
			
			cm.findCommunities(null,cs,cc);
		}
		
		override protected function wizResult(data:Object):void
		{
			mod.communitiesCollection = new ArrayCollection();
			mod.communitiesDic = new Dictionary(true);
			
			if(data && data.result)
			{
				var myColl:ArrayCollection = (data.result as CommunityList).communities;
				for(var i:int=0;i<myColl.length;i++)
				{
					var com:Community = myColl.getItemAt(i) as Community;
					
					var comvo:CommunityVO = new CommunityVO(com);
				
					if(comvo.isUniverse())
					{
						mod.communitiesCollection.addItem(comvo);
						mod.communitiesDic[comvo.universe] = comvo;
					}
					else
					{
						var universe:CommunityVO = mod.communitiesDic[comvo.universe] as CommunityVO;
						
						if(universe)
						{
							universe.addChild(comvo);
						}
					}
				}
				
				trace('mapping communities ok');
			}
		}
		
		override protected function wizFault(info:Object):void
		{
			trace('unable to find communities',info);
		}
	}
}